package cn.sc.pai.test;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.ViewDragHelper;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;

/**
 * description：使用ViewDragHelper
 * author：pany
 * on 2018/9/19 10:55
 */
public class SwipeBackDragLayout extends FrameLayout {

    private ViewDragHelper viewDrag;
    private View childDrag;
    private OnSwipeListener onSwipeListener;

    public SwipeBackDragLayout(@NonNull Context context) {
        super(context);
        init();
    }

    public SwipeBackDragLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        viewDrag = ViewDragHelper.create(this, 1.0f, viewDragCallback);
        //滑动左边缘还是右边缘：EDGE_LEFT和EDGE_RIGHT检测
        viewDrag.setEdgeTrackingEnabled(ViewDragHelper.EDGE_LEFT);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return viewDrag.shouldInterceptTouchEvent(ev);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        viewDrag.processTouchEvent(event);
        return true;
    }

    private ViewDragHelper.Callback viewDragCallback = new ViewDragHelper.Callback() {

        //系统会依次列出这个父容器的子视图，你需要指定当前传入的这个视图是否可拖动
        @Override
        public boolean tryCaptureView(View child, int pointerId) {
            if (childDrag == null) {
                childDrag = child;
            }
            return true;
        }

        //能滑动的最大（或者负向最大）的横向坐标
        @Override
        public int clampViewPositionHorizontal(View child, int left, int dx) {
            int rightLimit = getMeasuredWidth();//右侧边界
            if (left > rightLimit) {
                return rightLimit;
            } else if (left < 0) {
                return 0;
            }
            return left;
        }

        //能滑动的最大（或者负向最大）的纵向坐标
        @Override
        public int clampViewPositionVertical(View child, int top, int dy) {
            return 0;
        }

        //当手指从子视图松开时，会调用这个函数，同时返回在x轴和y轴上当前的速度
        @Override
        public void onViewReleased(View releasedChild, float xvel, float yvel) {
            super.onViewReleased(releasedChild, xvel, yvel);
            if (xvel >= 0) {//右滑
                if (xvel > 2000 || releasedChild.getLeft() > getMeasuredWidth() / 2) {
                    endAnimate();
                } else {
                    recoverAnimate();
                }
            } else {
                if (releasedChild.getLeft() > 0) {
                    recoverAnimate();
                }
            }
        }
    };

    /**
     * 恢复动画
     */
    private void recoverAnimate() {
        ValueAnimator animator = ValueAnimator.ofInt(childDrag.getLeft(), 0);
        animator.setDuration(300);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int value = (int) animation.getAnimatedValue();
                childDrag.setLeft(value);
            }
        });
        animator.start();
    }

    /**
     * 结束动画
     */
    private void endAnimate() {
        ValueAnimator animator = ValueAnimator.ofInt(childDrag.getLeft(), getMeasuredWidth());
        animator.setDuration(300);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int value = (int) animation.getAnimatedValue();
                childDrag.setLeft(value);
            }
        });
        animator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                if (onSwipeListener != null) {
                    onSwipeListener.onSwipeFinish();
                }
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        animator.start();
    }

    public void setOnSwipeListener(OnSwipeListener onSwipeListener) {
        this.onSwipeListener = onSwipeListener;
    }

    interface OnSwipeListener {
        void onSwipeFinish();
    }
}
